/*
 * Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 * This file is part of e3pool.
 *
 * e3pool is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * e3pool is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with e3pool. If not, see <https://www.gnu.org/licenses/>.
 */

package go_pool

import (
	"gitee.com/ameise84/e3ds/deque"
	"gitee.com/ameise84/e3lock"
)

var _gWorkPool = pool{
	IDeque: deque.NewDequeLock[*worker](&e3lock.SpinLock{}, 16),
}

func setPoolSize(cnt uint16) {
	newCache := deque.NewDequeLock[*worker](&e3lock.SpinLock{}, int(cnt))
	vs, _ := _gWorkPool.IDeque.PopBackAll()
	for _, v := range vs {
		if err := newCache.PushFront(v); err != nil {
			break
		}
	}
	_gWorkPool.IDeque = newCache
	return
}

func goWorkerDo(f GoAsyncFunc, args ...any) {
	w := getWorker()
	t := newTask(nil, f, args)
	w.submit(t)
}

type pool struct {
	deque.IDeque[*worker]
}

func getWorker() *worker {
	if w, err := _gWorkPool.PopFront(); err == nil {
		return w
	}
	return newWorker()
}

func putWorker(w *worker) {
	if err := _gWorkPool.PushFront(w); err != nil {
		w.submit(nil)
		releaseWorker(w)
	}
}
